package gocomm

import (
	"bytes"
	"encoding/base64"
	"net/http"
	"os"
	"bufio"
	"strings"
	"io"
)

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

//一行行读取文件
func ReadLine(fileName string, handler func(string)) error {
	f, err := os.Open(fileName)
	if err != nil {
		return err
	}
	buf := bufio.NewReader(f)
	for {
		line, err := buf.ReadString('\n')
		line = strings.TrimSpace(line)
		handler(line)
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}
	}
	return nil
}

// 写一行到文件
func WriteLine(fileName string,content string) error {
	f,err:=os.OpenFile(fileName,os.O_APPEND|os.O_CREATE,os.ModeAppend)
	/*err:=ioutil.WriteFile(fileName,[]byte(content+"\n"),os.ModeAppend)
	return err*/
	if err!=nil{
		return err
	}
	_,err=f.WriteString(content+"\n")
	return err
}


func GetFile(url string) ([]byte,error)  {
	pict_file, err := http.Get(url)
	if err != nil {
		return nil,err
	}
	defer pict_file.Body.Close()

	buf := new(bytes.Buffer)
	buf.ReadFrom(pict_file.Body)
	return buf.Bytes(),nil

}

func GetFile2(url string) (*bytes.Buffer,error) {
	req, _ := http.NewRequest("GET", url, nil)
	req.Header.Set("Connection", "close")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil,err
	}

	defer resp.Body.Close()

	buf := new(bytes.Buffer)
	buf.ReadFrom(resp.Body)

	return buf,nil
}

func HttpFileToBase64(url string) (string,error)  {

	buf,err:=GetFile2(url)
	if err!=nil{
		return "",err
	}

	return base64.StdEncoding.EncodeToString(buf.Bytes()),nil

}
